package captcha

import (
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"log"
	"server/utils/db"
	"server/utils/gin_helper"
)

func NewCaptcha(c *gin.Context) (base64 string) {
	//生成验证码
	driver := base64Captcha.NewDriverDigit(80, 160, 4, 0.7, 80)
	captcha := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
	_, b64s, answer, err := captcha.Generate()
	if err != nil {
		log.Println("生成验证码失败：", err)
		return
	}
	cacheKey := gin_helper.GetClientKey(c, "captcha")
	db.SetCacheKeyValue(cacheKey, answer, 60*5)
	//返回给客户端
	base64 = b64s
	return
}

func Check(c *gin.Context, captchaInput string) bool {
	cacheKey := gin_helper.GetClientKey(c, "captcha")
	return captchaInput == db.GetCacheValue(cacheKey)
}
